package com.atguigu.flink.chapter05.source;

import com.atguigu.flink.bean.WaterSensor;
import org.apache.flink.configuration.Configuration;
import org.apache.flink.streaming.api.datastream.DataStreamSource;
import org.apache.flink.streaming.api.environment.StreamExecutionEnvironment;
import org.apache.flink.streaming.api.functions.source.SourceFunction;

import java.io.BufferedReader;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.net.Socket;
import java.nio.charset.StandardCharsets;


/**
 * @author liuyun
 * @title: Flink04_Source_Custom
 * @projectName flink0924
 * @description: TODO
 * @date 2022-3-1 23:32
 */
public class Flink04_Source_Custom {
    /**
     * @param
     * @return
     * @description: TODO
     * @author liuyun
     * @date 2022-3-3 00:06
     */
    public static void main(String[] args) {
        Configuration conf = new Configuration();
        conf.setInteger("rest.port", 20000);
        StreamExecutionEnvironment env = StreamExecutionEnvironment.getExecutionEnvironment(conf);
        env.setParallelism(1);

        DataStreamSource<WaterSensor> stream = env.addSource(new SocketSource("hadoop162", 9999));
        stream.print();
        try {
            env.execute();
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    /**
     * @param
     * @author liuyun
     * @description: TODO
     * @return
     * @date 2022-3-3 00:06
     */
    public static class SocketSource implements SourceFunction<WaterSensor> {
        private String host;
        private int port;
        private boolean inCancel;

        public SocketSource(String host, int port) {
            this.host = host;
            this.port = port;
        }

        @Override
        public void run(SourceContext<WaterSensor> ctx) throws Exception {
            Socket socket = new Socket(host, port);

            InputStream inputStream = socket.getInputStream();

            BufferedReader reader = new BufferedReader(
                    new InputStreamReader(inputStream, StandardCharsets.UTF_8)
            );

            String line = reader.readLine();

            while (!inCancel && line != null) {
                String[] data = line.split(",");
                ctx.collect(new WaterSensor(data[0], Long.valueOf(data[1]), Integer.valueOf(data[2])));
                line = reader.readLine();
            }

        }

        /**
         * @param
         * @return
         * @description: TODO
         * @author liuyun
         * @date 2022-3-3 00:06
         */
        @Override
        public void cancel() {
            inCancel = true;
        }
    }
}

